package com.clear.club.circle.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.clear.club.circle.api.common.PageInfo;
import com.clear.club.circle.api.common.PageResult;
import com.clear.club.circle.api.enums.IsDeletedFlagEnum;
import com.clear.club.circle.api.enums.IsReadFlagEnum;
import com.clear.club.circle.api.req.GetShareMessageReq;
import com.clear.club.circle.api.vo.ShareMessageVO;
import com.clear.club.circle.server.dao.ShareMessageMapper;
import com.clear.club.circle.server.entity.po.ShareMessage;
import com.clear.club.circle.server.service.ShareMessageService;
import com.clear.club.circle.server.websocket.ChickenSocket;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ShareMessageServiceImpl extends ServiceImpl<ShareMessageMapper, ShareMessage> implements ShareMessageService {

    @Resource
    private ChickenSocket chickenSocket;

    /**
     * 查询当前用户是否有未读消息
     */
    @Override
    public Boolean unRead() {
        // 只统计发给当前用户的，且未读未被删除的消息的数量
        // 例如：select count(1) from share_message where to_id = '小黑子卤出鸡脚' and is_read = 2  and is_deleted = 0;
        LambdaQueryWrapper<ShareMessage> queryWrapper = Wrappers.<ShareMessage>lambdaQuery()
                // todo 暂时写死
                .eq(ShareMessage::getToId, "小黑子卤出鸡脚")
                .eq(ShareMessage::getIsRead, IsReadFlagEnum.UN_READ.getCode())
                .eq(ShareMessage::getIsDeleted, IsDeletedFlagEnum.UN_DELETED.getCode());
        return this.count(queryWrapper) > 0;
    }

    /**
     * 分页查询消息
     */
    @Override
    public PageResult<ShareMessageVO> getMessages(GetShareMessageReq req) {
        LambdaQueryWrapper<ShareMessage> queryWrapper = Wrappers.<ShareMessage>lambdaQuery()
                // todo 暂时写死
                .eq(ShareMessage::getToId, "小黑子卤出鸡脚")
                .eq(ShareMessage::getIsRead, req.getIsRead())
                .eq(ShareMessage::getIsDeleted, IsDeletedFlagEnum.UN_DELETED.getCode())
                .orderByDesc(ShareMessage::getId);
        PageInfo pageInfo = req.getPageInfo();
        // 1.分页查询，new Page()的两个参数分别是：页码、每页大小
        Page<ShareMessage> page = new Page<>(pageInfo.getPageNo(), pageInfo.getPageSize());
        Page<ShareMessage> pageRes = this.page(page, queryWrapper);   // page == pageRes
        List<ShareMessage> records = pageRes.getRecords();
        // 2.更新查询到的消息的状态
        if (CollectionUtils.isNotEmpty(records)) {
            // 更新消息状态
            // a.采集消息id
            List<Long> ids = records.stream().map(ShareMessage::getId).collect(Collectors.toList());
            // b.更新消息状态  未读 ==> 已读
            LambdaUpdateWrapper<ShareMessage> updateWrapper = Wrappers.<ShareMessage>lambdaUpdate()
                    .set(ShareMessage::getIsRead, IsReadFlagEnum.READ.getCode())
                    .in(ShareMessage::getId, ids);
            this.update(updateWrapper);
        }

        // 3.查询结果类型转换 po ==> vo
        PageResult<ShareMessageVO> result = new PageResult<>();
        List<ShareMessageVO> collect = records.stream().map(item -> {
            ShareMessageVO vo = new ShareMessageVO();
            vo.setId(item.getId());
            // todo 我有一事不明：ShareMessageVO的消息内容为什么使用 private Map<String, Object> content;
            vo.setContent(JSON.parseObject(item.getContent()));
            vo.setCreatedTime(item.getCreatedTime());
            return vo;
        }).collect(Collectors.toList());
        result.setRecords(collect);
        result.setTotal((int) pageRes.getTotal());
        result.setPageNo(pageInfo.getPageNo());
        result.setPageSize(pageInfo.getPageSize());

        return result;
    }

    @Override
    public void comment(String fromId, String toId, Long targetId) {
        JSONObject message = new JSONObject();
        // 1=评论 2=回复
        message.put("msgType", "COMMENT");
        message.put("msg", "评论了你的内容，快来看看把");
        message.put("targetId", targetId);
        ShareMessage shareMessage = new ShareMessage();
        shareMessage.setFromId(fromId);
        shareMessage.setToId(toId);
        shareMessage.setContent(message.toJSONString());
        shareMessage.setIsRead(IsReadFlagEnum.UN_READ.getCode());   // 未读
        shareMessage.setCreatedBy(fromId);
        shareMessage.setCreatedTime(new Date());
        shareMessage.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        ChickenSocket socket = chickenSocket.getChickenSocket(toId);
        if (Objects.nonNull(socket)) {
            chickenSocket.sendMessage(shareMessage.getContent(), socket.getSession());
        }
        this.save(shareMessage);

    }

    @Override
    public void reply(String fromId, String toId, Long targetId) {
        JSONObject message = new JSONObject();
        // 1=评论 2=回复
        message.put("msgType", "COMMENT_REPLY");
        // todo 暂时写死
        message.put("msg", String.format("%s 回复了你的评论，快来看看把！", "狗"));
        message.put("targetId", targetId);
        ShareMessage shareMessage = new ShareMessage();
        shareMessage.setFromId(fromId);
        shareMessage.setToId(toId);
        shareMessage.setContent(message.toJSONString());
        shareMessage.setIsRead(IsReadFlagEnum.UN_READ.getCode());   // 未读
        shareMessage.setCreatedBy(fromId);
        shareMessage.setCreatedTime(new Date());
        shareMessage.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        ChickenSocket socket = chickenSocket.getChickenSocket(toId);
        if (Objects.nonNull(socket)) {
            chickenSocket.sendMessage(shareMessage.getContent(), socket.getSession());
        }
        this.save(shareMessage);

    }
}
